package com.mediacenter.activity;

import java.lang.reflect.Method;
import java.util.List;

import android.app.ActivityGroup;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.mediacenter.AppConstants;
import com.mediacenter.R;

@SuppressWarnings("deprecation")
public class MainActivity extends ActivityGroup {

	private ViewFlipper mViewFlipper;
	private GridView menuGridView;
	// 底部菜单的名字
	private String[] menuGridViewNames = null;
	// 未选择时 显示的图片资源id
	private int[] menuGridViewUnSelectedImgs = null;
	// 选择时 显示的图片资源id
	private int[] menuGridViewSelectedImgs = null;
	// 上次点击的位置，当前点击的位置
	private int lastClickPosition, clickPosition;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.main);
		initRes();
		findViews();
		setValues();
		setListeners();
	}

	private void findViews() {
		menuGridView = (GridView) this.findViewById(R.id.gridview);
		mViewFlipper = (ViewFlipper) this.findViewById(R.id.content);
	}

	private void setValues() {
		menuGridView.setAdapter(new BottomMenuGridView(this));
		menuGridView.setNumColumns(4);
		menuGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		menuGridView.setGravity(Gravity.CENTER);
		menuGridView.setBackgroundResource(R.drawable.tab_bg);

		switchActivity(AppConstants.MEDIACENTER_ACTIVITY_INDEX);

	}

	private void initRes() {
		menuGridViewNames = new String[4];
		menuGridViewNames[0] = this.getString(R.string.tab_collect);
		menuGridViewNames[1] = this.getString(R.string.tab_online);
		menuGridViewNames[2] = this.getString(R.string.tab_manager);
		menuGridViewNames[3] = this.getString(R.string.tab_more);

		menuGridViewUnSelectedImgs = new int[4];
		menuGridViewUnSelectedImgs[0] = R.drawable.tab_rank_normal;
		menuGridViewUnSelectedImgs[1] = R.drawable.tab_category_normal;
		menuGridViewUnSelectedImgs[2] = R.drawable.tab_app_unselect;
		menuGridViewUnSelectedImgs[3] = R.drawable.tab_home_normal;

		menuGridViewSelectedImgs = new int[4];
		menuGridViewSelectedImgs[0] = R.drawable.tab_rank_selected;
		menuGridViewSelectedImgs[1] = R.drawable.tab_category_selected;
		menuGridViewSelectedImgs[2] = R.drawable.tab_app_select;
		menuGridViewSelectedImgs[3] = R.drawable.tab_home_selected;
	}

	private void setListeners() {
		menuGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				lastClickPosition = clickPosition;
				clickPosition = position;
				if (lastClickPosition == clickPosition)
					return; // 防止重复点击同一个菜单

				RelativeLayout temp = (RelativeLayout) menuGridView.getChildAt(position);
				temp.setBackgroundResource(R.drawable.bt_up_focus);
				temp.getChildAt(0).setBackgroundResource(menuGridViewSelectedImgs[position]);
				
				for (int i = 0; i < menuGridViewNames.length; i++) {
					if (i != position) {
						RelativeLayout temp2 = (RelativeLayout) menuGridView.getChildAt(i);
						temp2.setBackgroundDrawable(null);
						temp2.getChildAt(0).setBackgroundResource(menuGridViewUnSelectedImgs[i]);
					}
				}

				switchActivity(position);
			}

		});

	}

	private void switchActivity(int index) {
		String activityId = null;
		Intent intent = null;

		switch (index) {
		case AppConstants.MEDIACENTER_ACTIVITY_INDEX:
			intent = new Intent(this, MediaCenterActivity.class);
			activityId = AppConstants.MEDIACENTER_ACTIVITY;
			break;

		case AppConstants.ONLINE_ACTIVITY_INDEX:
			intent = new Intent(this, OnlineActivity.class);
			activityId = AppConstants.ONLINE_ACTIVITY;
			break;

		case AppConstants.RANK_ACTIVITY_INDEX:
			intent = new Intent(this, CollectActivity.class);
			activityId = AppConstants.RANK_ACTIVITY;
			break;

		case AppConstants.LOCAL_MANAGER_ACTIVITY_INDEX:
//			openCLD("com.sand.airdroid", this); 
			
			break;
		}

		if (activityId != null) {
			toActivity(activityId, intent);
		}

	}
	//启动其它应用
	public static void openCLD(String packageName,Context context) {
		PackageManager packageManager = context.getPackageManager();
		PackageInfo pi = null;
		
			try {
				
				pi = packageManager.getPackageInfo(packageName, 0);
			} catch (NameNotFoundException e) {
				
			}
			Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
//			resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
			resolveIntent.setAction("com.sand.airdroid.action.connection");
			resolveIntent.setPackage(pi.packageName);

			List<ResolveInfo> apps = packageManager.queryIntentActivities(resolveIntent, 0);

			ResolveInfo ri = apps.iterator().next();
			if (ri != null ) {
				String className = ri.activityInfo.name;

				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.setAction("com.sand.airdroid.action.connection");
				ComponentName cn = new ComponentName(packageName, className);

				intent.setComponent(cn);
				context.startActivity(intent);
			}
	}
	/**
	 * 切换到指定activity
	 * 
	 * @param activityId
	 * @param intent
	 */
	public void toActivity(String activityId, Intent intent) {
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		View view = getLocalActivityManager().startActivity(activityId, intent).getDecorView();
		// 切换activity时显示的动画效果
//		 view.setAnimation(new WindowAnimation(500));
		if (mViewFlipper.getChildCount() > 0 && mViewFlipper.getDisplayedChild() != 0) {
			mViewFlipper.removeViewAt(mViewFlipper.getDisplayedChild());
		}
		mViewFlipper.addView(view);
		mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(view));
		// mViewFlipper.showNext();
	}

	private class BottomMenuGridView extends BaseAdapter {

		private LayoutInflater mInflater;

		public BottomMenuGridView(Context ctx) {
			this.mInflater = LayoutInflater.from(ctx);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return menuGridViewUnSelectedImgs.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			MenuViewHolder viewHolder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_tab, null);
				viewHolder = new MenuViewHolder();
				viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image_item);
				viewHolder.textView = (TextView) convertView.findViewById(R.id.text_item);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (MenuViewHolder) convertView.getTag();
			}
			viewHolder.imageView.setBackgroundResource(menuGridViewUnSelectedImgs[position]);
			viewHolder.textView.setText(menuGridViewNames[position]);

			return convertView;
		}

	}

	private final class MenuViewHolder {
		public ImageView imageView;
		public TextView textView;
	}

	public static void resetSelect(View view) {
		try {  
            @SuppressWarnings("unchecked")  
            Class<GridView> c = (Class<GridView>) Class.forName("android.widget.GridView");  
            Method[] flds = c.getDeclaredMethods();  
            for (Method f : flds) {  
                if ("setSelectionInt".equals(f.getName())) {  
                    f.setAccessible(true);  
                    f.invoke(view,new Object[] { Integer.valueOf(-1) });  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
	}
}
